const client = require('./redis_client');

const slug_key = "slug.to.id";
const post_views_key = "posts:page:views";
const latest_posts_key = "latest:posts";

async function get_post_id() {
    return await client.incr('post:count');
}

function generate_slug(title) {
    return title.replace(/\s+/g, '-').toLowerCase();
}

async function save_post(post) {
    let tags = post.tags.split(',');
    let id = await get_post_id();
    let slug = generate_slug(post.title);
    let is_slug_avaible = await client.hSetNX(slug_key, slug, `${id}`);
    if (is_slug_avaible) {
        await client.hSet(`post:${id}`, {...post, slug: slug});
        await client.zAdd(latest_posts_key, {score: Date.now(), value: `${id}`});
        await client.zAdd(post_views_key, {score: 0, value: `${id}`});
        tags.forEach(async tag => {
            if (tag === "") return;
            await client
                .multi()
                .sAdd(`post:${id}:tags`, tag)
                .sAdd(`tag:${tag}:posts`, `${id}`)
                .exec();
        });
        return slug;
    }
    return "";
}

async function get_article(slug) {
    let id = await client.hGet(slug_key, slug);
    let article = await client.hGetAll(`post:${id}`);
    //add view count
    await client.zIncrBy(post_views_key, 1, `${id}`);
    return article;
}

async function get_hot_list() {
    let views_list = await client.zRangeWithScores(post_views_key, 0, 9, {REV: 1});
    //assemble list of posts
    let posts = [];
    for (let i = 0; i < views_list.length; i++) {
        let post = await client.hGetAll(`post:${views_list[i].value}`);
        //remove unnecessary fields
        delete post['content'];
        delete post['tags'];
        delete post['date'];
        post['views'] = views_list[i].score;
        posts.push(post);
    }
    return posts;
}

module.exports = {
    save_post: save_post,
    get_article: get_article,
    get_hot_list: get_hot_list
}
